package cn.com.flever.app;


import cn.com.flever.app.config.SysConfig;
import cn.com.flever.app.handler.AbstractHandler;
import cn.com.flever.app.handler.PCRunHandler;
import cn.com.flever.app.socket.ReconnectingWebSocketClient;
import cn.com.flever.app.utils.EncryptionUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@Slf4j
public class Main {

    public static WebSocketClient client;

    public static Properties sysConfig=SysConfig.getConfiguration();

    private static HashMap<String, AbstractHandler> handlerMap=new HashMap<>();

    static {
        handlerMap.put("pc", new PCRunHandler());
    }

    public static void main(String[] args) {
        try {
            client = new ReconnectingWebSocketClient(new URI(sysConfig.getProperty("server.netty.url")),new Draft_6455()) {
                @Override
                public void open(ServerHandshake handshakedata) {
                    log.info("握手成功");
                }

                @Override
                public void message(String msg) {
                    //解密消息
                    JSONObject req=JSONObject.parseObject(msg);
                    //根据类型调用handler
                    String type=req.getString("type");
                    AbstractHandler handler = handlerMap.get(type);
                    //handler派发
                    JSONObject res=handler.dispacher(req,this);
                }
                @Override
                public void close(int code, String reason, boolean remote) {
                    log.info("链接已关闭");
                }

                @Override
                public void error(Exception ex) {
                }
            };
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        client.connect();
    }

    /**
     * 连接服务端
     * @return
     */
    public static void clientUp()
    {
        //连接成功,发送客户端启动信息
        JSONObject clientUp=new JSONObject();
        clientUp.put("token",SysConfig.getConfiguration().getProperty("client.token"));
        clientUp.put("type","pc");
        clientUp.put("uuid", UUID.randomUUID().toString());
        clientUp.put("method", "clientUp");
        client.send(EncryptionUtils.encrypt(clientUp.toJSONString()));
    }
}
